package cn.project.engineering.http

import android.text.TextUtils
import cn.project.engineering.constant.LiveEventBusConstant
import cn.project.engineering.http.bean.RequestError
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.jeremyliao.liveeventbus.LiveEventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.ConnectException
import java.net.UnknownHostException

/**
 *
 * @author  lifuhai
 * @date 2021/2/18 15:19
 */
interface RequestCallback2<T> : Callback<ResponseParent<T>> {

    fun onRequestSuccess(body: T?)

    fun onRequestFail(error: RequestError)

    override fun onFailure(call: Call<ResponseParent<T>>, t: Throwable) {
        var message=""
        if ((t is ConnectException) || (t is UnknownHostException)) {
            message= "网络连接失败，请检查网络设置"
//            LiveEventBus.get(LiveEventBusConstant.INTERNET).post("");
        } else {
            if (!TextUtils.isEmpty(t.message)) {
                message= t.message!!
            } else {
                message= "未知错误"
            }
        }
        onRequestFail(RequestError().apply {
            this.message = message
        })
    }

    override fun onResponse(call: Call<ResponseParent<T>>, response: Response<ResponseParent<T>>) {
        when (response.code()) {
            200 -> {
                val body = response.body();
                if (body != null) if (body.code==200)
                        onRequestSuccess(body!!.data)
            }
            else -> {
                val errorBodyString = response.errorBody()?.string()

                if (TextUtils.isEmpty(errorBodyString)) {
                    onRequestFail(RequestError().apply {
                        this.message = response.message()
                    })
                } else {
                    try {
                        onRequestFail(Gson().fromJson(errorBodyString, RequestError::class.java))
                    } catch (e: JsonSyntaxException) {
                        onRequestFail(RequestError().apply {
                            this.code = -1
                            this.message = errorBodyString
                        })
                    }
                }
            }
        }
    }
}